import React from 'react';
import { useMachine } from '@xstate/react';
import { redditMachine } from './redditMachine';

const subreddits = ['', 'frontend', 'reactjs', 'vuejs'];

function App() {
  const [current, send] = useMachine(redditMachine);
  const { subreddit, posts } = current.context;

  return (
    <main>
      <header>
        <select onChange={(e) => {
          send({ type: 'SELECT', name: e.target.value });
        }}>
          {
            subreddits.map(item => {
              return <option key={item}>{item}</option>
            })
          }
        </select>
      </header>
      <section>
        <h1>{current.matches('idle') ? 'Select a subreddit' : subreddit}</h1>
        {current.matches({ selected: 'loading' }) && <div>Loading...</div>}
        {current.matches({ selected: 'loaded' }) && posts && (
          <ul>
            {
              posts.map((post) => <li key={post.title}>{post.title}</li>)
            }
          </ul>
        )}
        {current.matches({ selected: 'failed' }) && '加载失败'}
      </section>
    </main>
  );
}

export default App;
